var driver_list = [];
var global_report_list = [];

function setRowColors() {
    $("#reportsTable tbody").removeClass('tableAlternateColor');
    $("#reportsTable tbody:odd").addClass('tableAlternateColor');
}

function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' +
                      json.tmpo_poc_name + '</a> ' +
                      'Phone: (' +
                      json.tmpo_poc_phone.substr(0,3) + ') ' +
                      json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    ); 
}

function sort_function(a,b){
    return a.id - b.id;
}


function getResources() {
    $.getJSON("/api/tmpo/resources/",
        function (json) {
           driver_list = jQuery.makeArray(
               $(json.drivers)
           ).sort( sort_function );
	         vehicle_list = jQuery.makeArray($(json.vehicles)).sort(
	             sort_function );
	      }
    );
}

function getReports() {
    $.getJSON("/api/tmpo/reports/", 
        function(json){
            global_report_list = json.report;
            writeReportRows(json.report);
            
        }
    );
}

function writeReportRows(report_list) {
    report_list = jQuery.makeArray($(report_list)).sort( sort_function );
    $("#reportsTable tbody, thead, caption, colgroup").remove();
    $("#button_div").html('<span id="button_add" class="button">'+
    '<img src="/tmpo/images/icons/add.gif" alt=""/>Add Report</span>');
    $("#reportsTable").html('<caption>Available Reports</caption>'+
    '<colgroup><col id="rReportCol" /><col id="rTitleCol" />'+
    '<col id="rFromCol" /><col id="rShowCol" /></colgroup><thead>'+
    '<tr><th scope="col">No.</th><th scope="col" colspan="3">'+
    'Report Details</th></tr></thead>');
    jQuery.map(report_list, function(row){
        row_contents = '';
        row_contents += '<tbody id="tbody_' + row.id +
        '"><tr><td><span class="hoverButton">Edit</span><h5>'+ row.id +
         '</h5></td><td><h5>' + row.title + '</h5></td><td>';
        row_contents += buildCustomFields(row.query);
	      row_contents += '</td><td><span id="button_generate_'+row.id+
	      '" class="button"><img src='+
	      '"/tmpo/images/icons/generate_report.gif" alt='+
	      '""/>Show Report</span><span id="button_print_' + row.id +
	      '" class="button"><img src="/tmpo/images/icons/print.gif" '+
	      'alt=""/>PDF</span></td></tr></tbody>';
        $("#reportsTable").append(row_contents);

        $("#button_generate_" + row.id).click(
            function () { 
	        writeReport(row.id, row.title);
            }
        );
        $("#button_print_" + row.id).click(
            function () {
                $("#resultsTable").remove();
                $("#reportsTable").after('<table id='+
                '"resultsTable" style="display:none;"></table>');
	        writeHiddenReport(row.id, row.title);
            }
        );
    });
    $("span#button_add").click(
        function () {
            writeAddRow();
        }
    );
    setRowColors();
    bindRows(report_list);
}

function buildCustomFields(query) {
    custom_fields = query.match(/\$\w+/gi);
    if(!custom_fields){
        return '';
    }

    //custom_fields = custom_fields.unique();
    custom_fields_html = [];

    if ( jQuery.inArray('$Driver',custom_fields) != -1 ){
        field_html = '';
        field_html += '<label>Driver:</label> <select name='+
        '"$Driver" id="$Driver">';
        jQuery.map(driver_list, function(n){
            field_html += '<option value=' + n.id +
            '>' + n.name + '</option>'; 
        });
        field_html += '</select>';
        custom_fields_html[custom_fields_html.length] = field_html;
        custom_fields = jQuery.grep(custom_fields, function(n, i){
            return (n != "$Driver"); });
    }
    if ( jQuery.inArray('$Vehicle',custom_fields) != -1 ){
        field_html = '';
        field_html += '<label>Vehicle:</label> '+
        '<select name="$Vehicle" id="$Vehicle">';
        jQuery.map(vehicle_list, function(n){
            field_html += '<option value=' + n.id +
            '>' + n.vehicleno + '</option>';
        });
        field_html += '</select>';
        custom_fields_html[custom_fields_html.length] = field_html;
        custom_fields = jQuery.grep(custom_fields, function(n, i){
            return (n != "$Vehicle"); });
    }
    if ( jQuery.inArray('$From',custom_fields) != -1 ){
        field_html = '';
        field_html += '<label>From:</label> <input name="$From" '+
        'id="$From" type="text" size="12" value=""/> <label>To:'+
        '</label> <input name="$To" id="$To" type="text" size='+
        '"12" value=""/>';
        custom_fields_html[custom_fields_html.length] = field_html;
        custom_fields = jQuery.grep(custom_fields, function(n, i){
            return (n != "$From" && n != "$To"); });
    }
    jQuery.map(custom_fields, function(field){
        field_html = '';
        field_html += '<label>' + field.substring(1) +
         ':</label> <input name="' + field + '" id="' + field +
          '" type="text" size="12" value=""/>';
        custom_fields_html[custom_fields_html.length] = field_html;
    });

    cell_contents = custom_fields_html.join('<br /><br />');
    return cell_contents;
}

function writeEditRow(row) {
    $("#reportsTable tbody").unbind();
    $("#reportsTable tbody tr td").unbind();
    $("#reportsTable tbody tr td:eq(3) span").unbind();
    $("#reportsTable tbody tr td span[class='button']").addClass(
    'buttonInactive');
    $("#reportsTable tbody tr td:eq(2) input, select").attr(
    {disabled: "true"});
    $("#reportsTable #tbody_" + row.id + " tr td:eq(0) span").remove();
    $("#reportsTable #tbody_" + row.id + " tr td:eq(1)").html(
    '<label>Report Title:</label><br/><input id="title" name='+
    '"title" type="text" size="25" value="' + row.title + '"/>');
    $("#reportsTable #tbody_" + row.id + " tr:eq(0)").after(
    '<tr><td>&nbsp;</td><td><label>Description</label><br/>'+
    '<textarea id="description" name="description" rows="7" '+
    'cols="25">' + row.description + '</textarea></td><td colspan="2">'+
    '<label>SQL Query for Report:</label><br/><textarea id="query"'+
    ' name="query" rows="7" cols="65">' + row.query + '</textarea>'+
    '</td></tr>');
    $("#reportsTable #tbody_" + row.id + " tr:eq(1)").after(
    '<tr><td colspan="4"><span id="button_save" class="button">'+
    '<img alt="" src="/tmpo/images/icons/save.gif"/>Save</span>'+
    '<span id="button_cancel" class="button"><img alt="" src='+
    '"/tmpo/images/icons/close.gif"/>Cancel</span><span id='+
    '"button_delete" class="button"><img alt="" src='+
    '"/tmpo/images/icons/delete.gif"/>Delete</span></td></tr>');
    $("#button_add").unbind();
    $("#button_add").addClass('buttonInactive');
    $("#button_save").click(
        function () { 
        $("#message").remove();
        $("#button_delete").after(
            '<span id="message" name="message" class="waitMessage">'+
            '<img src="/tmpo/images/icons/hourglass.gif" alt="" />'+
            'Your changes are being saved. Please wait.</span>');
	    postReport(row.id);
        }
    );
    $("#button_cancel").click(
        function () { 
	    getReports();
        }
    );
    $("#button_delete").click(
        function () { 
	    deleteReport(row);
        }
    );
}

function writeAddRow() {
    $("#button_add").unbind();
    $("#button_add").addClass('buttonInactive');
    $("#reportsTable tbody").unbind();
    $("#reportsTable tbody tr td").unbind();
    $("#reportsTable tbody tr td span[class='button']").addClass(
    'buttonInactive');
    $("#reportsTable tbody tr td:eq(2) input, select").attr(
    {disabled: "true"});
    $("#reportsTable thead").after('<tbody class="highlight">'+
    '<tr><td>&nbsp;</td><td><label>Report Title:</label><br/>'+
    '<input type="text" value="" size="25" name="title" id="title"/>'+
    '</td><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>'+
    '<label>Description</label><br/><textarea cols="25" rows="7" '+
    'name="description" id="description"></textarea></td><td '+
    'colspan="2"><label>SQL Query for Report:</label><br/>'+
    '<textarea cols="65" rows="7" name="query" id="query"></textarea>'+
    '</td></tr><tr><td colspan="4"><span class="button" id='+
    '"button_save"><img src="/tmpo/images/icons/save.gif" alt=""/>'+
    'Save</span><span class="button" id="button_cancel"><img src='+
    '"/tmpo/images/icons/close.gif" alt=""/>Cancel</span></td></tr>'+
    '</tbody>');
    $("#button_save").click(
        function () {
        $("#message").remove();
        $("#button_cancel").after(
            '<span id="message" name="message" class="waitMessage">'+
            '<img src="/tmpo/images/icons/hourglass.gif" alt="" />'+
            'Your changes are being saved. Please wait.</span>'); 
	    putReport();
        }
    );
    $("#button_cancel").click(
        function () { 
	    getReports();
        }
    );
}

function putReport() {
    report_data = {};
    report_data.title = $("#title").val();
    report_data.description = $("#description").val();
    report_data.query = $("#query").val();
    $.ajax({
        type: "PUT",
        url: '/api/tmpo/reports/',
        data: report_data,
        dataType: "string",
        success: function(){
            getReports();
        },
        error: function(string){
            $("#message").remove();
            if(string.status == 409){
                $("#button_cancel").after('<span id="message" '+
                'name="message" class="generalErrorMessage">'+
                '<img src="/tmpo/images/icons/error.gif" alt="" />'+
                'The query can not contain Insert, Delete, Create or '+
                'Drop.</span>');    
            }else{
                $("#button_cancel").after('<span id="message" name='+
                '"message" class="generalErrorMessage"><img src='+
                '"/tmpo/images/icons/error.gif" alt="" />Unable to '+
                'save at this time.</span>');
            }
        }
    });
}

function postReport(key) {
    report_data = {};
    report_data.title = $("#title").val();
    report_data.description = $("#description").val();
    report_data.query = $("#query").val();
    $.ajax({
        type: "POST",
        url: '/api/tmpo/reports/' + key + '/',
        data: report_data,
        success: function(){
            getReports();
        },
        error: function(string){
            $("#message").remove();
            if(string.status == 409){
                $("#button_delete").after('<span id="message" name='+
                '"message" class="generalErrorMessage"><img src='+
                '"/tmpo/images/icons/error.gif" alt="" />'+
                'The query can not contain Insert, Delete, Create '+
                'or Drop.</span>');    
            }else{
                $("#button_delete").after('<span id="message" name='+
                '"message" class="generalErrorMessage"><img src='+
                '"/tmpo/images/icons/error.gif" alt="" />Unable to'+
                ' save at this time.</span>');
            }
        }
    });
}

function deleteReport(key) {
    var deleteCommitment = function(){
        $.ajax({
            type: "DELETE",
            url: '/api/tmpo/reports/' + key.id + '/',
            dataType: "text",
            success: function(){
                getReports();
            },
            error: function(){
                $("#message").remove();
                $("#button_delete").after('<span id="message" name='+
                '"message" class="generalErrorMessage"><img src='+
                '"/tmpo/images/icons/error.gif" alt="" />Unable to'+
                ' delete at this time.</span>');
            }
        });
        clearTimeout(timeout_index);
        delete timeout_index;
    };
    timeout_index = setTimeout(deleteCommitment, 10000);
    $(window).unload( function (){
        if( typeof(timeout_index) != 'undefined' ){ 
            deleteCommitment();
        }
    });
    $("#tbody_"+key.id).before('<tbody id="delete_row"><tr><td colspan="4"><b>'+
        'This report has been deleted. <span id="close_delete_'+key.id+'"'+
        ' class="inferLink"><u>Close</u></span> | <span id="undo_delete_'+ 
        key.id+'" class="inferLink"><u>Undo</u></span></b></td></tr></tbody>');
    $("#tbody_"+key.id).remove();
    bindRows(global_report_list);
    $("#close_delete_" + key.id).click(function () {
        deleteCommitment(); 
        getReports();
        return false;
    });
    $("#undo_delete_" + key.id).click(function () {
        clearTimeout(timeout_index); 
        delete timeout_index;
        getReports();
        return false; 
    });
}

function writeReport(key, title) {
    field_list = $("#tbody_" + key + " tr td:nth-child(3) :input");
    field_data = {};
    field_data.GarbageFormField = '';
    jQuery.map(field_list, function(field){
        field_data[field.name] = field.value;
    });
    $.ajax({
        type: "POST",
        url: '/api/tmpo/report_results/' + key + '/',
        data: field_data,
        dataType:"json",
        success: function(json){
            $("#button_div").html('<span id="button_print" '+
            'class="button"><img alt="" src='+
            '"/tmpo/images/icons/print.gif"/>PDF</span>');
            $("#reportsTable").empty();
            $("#reportsTable").append('<caption>'+title+'</caption>');
            $("#reportsTable").append(writeReportHeader(json.columns));
            $("#reportsTable").append(writeReportData(
            json.data, json.columns.length));
	    $("#button_print").click( makePrinter("#reportsTable") );
        }
    });
}

function writeHiddenReport(key, title) {
    field_list = $("#tbody_" + key + " tr td:nth-child(3) :input");
    field_data = {};
    field_data.GarbageFormField = '';
    jQuery.map(field_list, function(field){
        field_data[field.name] = field.value;
    });
    $.ajax({
        type: "POST",
        url: '/api/tmpo/report_results/' + key + '/',
        data: field_data,
        dataType:"json",
        async:false,
        success: function(json){
            $("#resultsTable").append('<caption>' + title +
             '</caption>');
            $("#resultsTable").append(writeReportHeader(json.columns));
            $("#resultsTable").append(writeReportData(
            json.data, json.columns.length));
            makePrinter("#resultsTable")();
        }
    });
}

function writeReportHeader(columns) {
    content = '';
    jQuery.map(columns, function(col){
        content += '<th>' + col + '</th>';
    });
    content = '<thead><tr>' + content + '</tr></thead>'; 
    return content;
}

function writeReportData(data, column_count) {
    content = '';
    if (data.length === 0){
        content += '<tr><td colspan="' + column_count +
         '">No Results.</td></tr>';
    }else{
        jQuery.map(data, function(data_row){
            content += '<tr>';
            jQuery.map(data_row, function(data_cell){
                content += '<td>' + data_cell + '</td>';            
            });        
            content += '</tr>';
        });
    }
    content = '<tbody>' + content + '</tbody>';
    return content;
}

function bindRows(report_list) {
    jQuery.map(report_list, function(row){
        $("#tbody_" + row.id).unbind();
        $("#tbody_" + row.id).hover(
            function () { $("#tbody_" + row.id).addClass(
            'highlight'); },
            function () { $("#tbody_" + row.id).removeClass(
            'highlight'); }
        );
        $("#tbody_" + row.id + " tr td").click(
            function () { writeEditRow(row); }
        );
        $("#tbody_" + row.id + " tr td:eq(2)").unbind();
        $("#tbody_" + row.id + " tr td:eq(3)").unbind();
    });
}

$(document).ready(function() {
    getSiteCfg();
    getResources();
    getReports();
});
